// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.preferencessync.internal.merge;

import com.google.appengine.preferencessync.internal.InternalSyncException;
import com.google.appengine.preferencessync.internal.SharedPreferencesUtils;
import com.google.appengine.syncserver.shared.PropertyChange;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Implements client wins strategy for merging. 
 */
public class ClientWinsHandler implements InternalMergeHandler {
  /**
   * Applies changes to client only if the key has not changed.
   * 
   * @throws InternalSyncException 
   */
  @Override
  public void merge(SharedPreferences clientPreferences,
      ArrayList<PropertyChange> clientChanges, ArrayList<PropertyChange> serverChanges) 
          throws InternalSyncException {
    Set<String> clientChangeSet = getKeySet(clientChanges);
    
    Editor editor = clientPreferences.edit();
    // Don't delete client key changes.
    for (PropertyChange change : serverChanges) {
      if (!clientChangeSet.contains(change.getKey())) {
        switch(change.getType()) {
          case DELETE:
            editor.remove(change.getKey());
            break;
          case UPDATE:
            SharedPreferencesUtils.putNamespacedStringAsObject(editor, change.getKey(),
                change.getValue());
            break;
        }
      }
    }
    editor.commit();
  }

  /**
   * Get the set of all keys in the changes.
   * 
   * @param changes
   * @return Set of keys in the changes.
   */
  private static Set<String> getKeySet(ArrayList<PropertyChange> changes) {
    Set<String> returnSet = new HashSet<String>();
    for (PropertyChange change : changes) {
      returnSet.add(change.getKey());
    }
    return returnSet;
  }
}
